<?php

declare(strict_types=1);

namespace App\Model;

use Hyperf\DbConnection\Model\Model;
use Hyperf\Database\Model\SoftDeletes;
// use App\Model\User;

/**
 * @property int $id 
 * @property string $username 
 * @property string $password 
 * @property string $nickname
 * @property string $avatar
 * @property string $token
 * @property string $expiration_at 
 * @property string $last_at
 * @property string $openid
 * @property string $session_key
 * @property string $unionid
 * @property string $wx_avatar
 * @property string $wx_nickname
 * @property int $mobile
 * @property \Carbon\Carbon $created_at 
 * @property \Carbon\Carbon $updated_at 
 * @property string $deleted_at 
 */
class User extends Model
{
    use SoftDeletes;
	
    /**
     * The table associated with the model.
     */
    protected ?string $table = 'user';

    /**
     * The attributes that are mass assignable.
     */
    protected array $fillable = [];

    /**
     * The attributes that should be cast to native types.
     */
    protected array $casts = ['id' => 'integer', 'created_at' => 'datetime', 'updated_at' => 'datetime'];

    /**
	 * @var bool
	 */
//    public bool $timestamps = false;

    // 登录
    public static function login($post)
    {
        $user = self::where(['username' => $post['username'],'password' => $post['password'],])->first();
        if (!$user) {
            $res['err'] = 1;
		  $res['msg'] = '登录失败，账号密码错误';
		  return $res;
        }

	   //更新token
	   $token = self::generateToken($user['id'],time());
	   if ($token) {
			$user->token = $token;
			$user->expiration_at = time()+60*60*24;
			$tokenRes = $user->save();
			if(!$tokenRes){
        			$res['err'] = 1;
				$res['msg'] = '登录成功，更新令牌失败';
				return $res;
        		}
        }else{
        		$res['err'] = 1;
			$res['msg'] = '登录成功，生成令牌失败';
			return $res;
        }

	   // 保存到本地缓存
	   $data['username'] = $user['username'];
	   $data['token'] = $token;
	   $data['id'] = $user['id'];
	   $data['nickname'] = $user['nickname'];
	   $data['avatar'] = $user['avatar'];
	   $res['err'] = 0;
	   $res['msg'] = '登录成功，正在跳转..';
	   $res['cookie'] = $data;
        return $res;
    }

    // 注册
    public static function register($post)
    {
        $user = self::where('username', $post['username'])->first();
        if ($user) {
            $res['err'] = 1;
		  $res['msg'] = '注册失败，账号重复';
		  return $res;
        }

	   $user = new User();
        $user->username = $post['username'];
        $user->password = $post['password'];
        $result = $user->save();

        if($result){
			$res['err'] = 0;
			$res['msg'] = '注册成功，正在跳转...';
        }else{
        		$res['err'] = 1;
			$res['msg'] = '注册失败，请重新注册';
        }
        return $res;
    }

    // 生成token
    public static function generateToken($userId, $timestamp) {
	    $input = $userId . $timestamp;  // 连接用户ID和时间戳
	    $hash = hash('sha256', $input);  // 使用SHA-256进行哈希运算
	    $token = substr(bin2hex($hash), 0, 32);  // 将哈希结果转换为16进制并截取前32位
	    return $token;
	}

	// 获取好友列表
    public static function getFriendList($token)
    {
    	   $userId = self::where('token', $token)->value('id');
        return self::where('id', '<>', $userId)->orderBy('id', 'asc')->get();
    }

    // 获取好友信息
    public static function friendDetail($friendid)
    {
        $friendDetail = self::where('id', $friendid)->first();
        $friendInfo['nickname'] = $friendDetail->nickname;
        $friendInfo['avatar'] = $friendDetail->avatar;
        return $friendInfo;
    }

    //修改个人信息
    public static function userEdit($formData){
	   $res = self::where('id', $formData['formdata']['id'])->update(['nickname'=>$formData['formdata']['nickname']]);
        return $res;
    }

    //修改头像
    public static function avatarEdit($id,$avatar){
    	   $avatarOld = self::where('id', $id)->value('avatar');
    	   if($avatarOld != $avatar){
			$res = self::where('id', $id)->update(['avatar'=>$avatar]);
			return $res;
    	   }
        return true;
    }
}
